from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

ds = load_iris()
x, y = ds.data[:, 0:2], ds.target
x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=1, test_size=50)

print(f"x shape: {x.shape}, y shape: {y.shape}")
print(f"x_1： 最小值{x[:, 0].min():.2f}，最大值{x[:, 0].max():.2f}，均值{x[:, 0].mean():.2f}，个数{x[:, 0].shape[0]}")
print(f"x_2： 最小值{x[:, 1].min():.2f}，最大值{x[:, 1].max():.2f}，均值{x[:, 1].mean():.2f}，个数{x[:, 1].shape[0]}")
print(f"x_train shape: {x_train.shape}, y_train shape: {y_train.shape}")
print(f"x_test shape: {x_test.shape}, y_test shape: {y_test.shape}")



from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score

model = LogisticRegression()
model.fit(x_train, y_train)

mc = model.score(x_test, y_test)
ac = accuracy_score(y_test, model.predict(x_test))
print(f"模型预测准确率（Score）：{mc}")
print(f"模型预测准确率（Accuracy）：{ac}")



# 导入Matplotlib与NumPy库
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import numpy as np
# 绘制分类界面
N, M = 500, 500  # 网格采样点的个数，采样点越多，分类界面图越精细
t1 = np.linspace(4, 8, N)  # 生成采样点的横坐标值
t2 = np.linspace(1.5, 5, M)  # 生成采样点的纵坐标值
print(f"t1： 最小值{t1.min():.2f}，最大值{t1.max():.2f}，均值{t1.mean():.2f}，个数{t1.shape[0]}")
print(f"t2： 最小值{t2.min():.2f}，最大值{t2.max():.2f}，均值{t2.mean():.2f}，个数{t2.shape[0]}")

x1, x2 = np.meshgrid(t1, t2)  # 生成网格采样点
x_new = np.stack((x1.flat, x2.flat), axis=1)  # 将采样点作为测试点
y_predict = model.predict(x_new)  # 预测测试点的值
y_hat = y_predict.reshape(x1.shape)  # 与x1设置相同的形状



iris_cmap = ListedColormap(["#ACC6C0", "#FF8080", "#A0A0FF"])  # 设置分类界面的颜色
plt.pcolormesh(x1, x2, y_hat, cmap=iris_cmap)  # 绘制分类界面
# 绘制3种类别鸢尾花的样本点
plt.scatter(x[y == 0, 0], x[y == 0, 1], s=30, c="g", marker="^", label="类别0")  # 绘制标签为0的样本点
plt.scatter(x[y == 1, 0], x[y == 1, 1], s=30, c="r", marker="o", label="类别1")  # 绘制标签为1的样本点
plt.scatter(x[y == 2, 0], x[y == 2, 1], s=30, c="b", marker="s", label="类别2")  # 绘制标签为2的样本点
# 设置坐标轴的名称并显示图形
plt.rcParams["font.sans-serif"] = "Simhei"
plt.xlabel("花萼长度")
plt.ylabel("花萼宽度")
plt.legend()
plt.show()